from peewee import *
from playhouse.pool import PooledMySQLDatabase
from datetime import datetime

db = PooledMySQLDatabase('test',
                         **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'user': 'lxgzhw001',
                            'password': 'lxgzhw001'},
                         max_connections=32,  # 最大连接数量
                         stale_timeout=300,  # 5 分钟
                         )


class BaseModel(Model):
    @property
    def to_dict(self) -> dict:
        data = self.__dict__.get('__data__')
        for k in data.keys():
            if isinstance(data.get(k), datetime):
                # 将日期类型转换为字符串类型
                data[k] = str(data[k])
        # 显式传回dict类型，方便编辑器有智能提示
        return data

    class Meta:
        database = db


class Employee(BaseModel):
    name = CharField()
    age = IntegerField()
    birthday = DateTimeField()

    class Meta:
        table_name = 'employee'


db.create_tables([Employee])
if __name__ == '__main__':
    # 批量插入元组
    # data = [
    #     ('李四1', 43, '2021-2-2'),
    #     ('李四2', 43, '2021-2-2'),
    #     ('李四3', 43, '2021-2-2'),
    #     ('李四4', 43, '2021-2-2'),
    #     ('李四5', 43, '2021-2-2'),
    #     ('李四6', 43, '2021-2-2'),
    #     ('李四7', 43, '2021-2-2'),
    # ]
    #
    # Employee.insert_many(data, fields=['name', 'age', 'birthday']).execute()

    # 查询数据
    query = Employee.select().first()
    print(query, type(query))
    print(query.to_dict)
